package com.lt.contract.controller;

import com.alibaba.fastjson.JSONObject;
import com.lt.contract.service.UploadExecutor;
import com.lt.report.util.VeDate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;

@Controller
@RequestMapping(value = "/contract")
@Slf4j
public class ContractUpload {

    @Autowired
    UploadExecutor uploadExecutor;
    @PostMapping(value = "/upload")
    @ResponseBody
    @CrossOrigin
    public String uploadExcel(HttpServletRequest request) {
        log.info("\n【请求地址】：{}\n【请求时间】：{}\n", "/upload", VeDate.getNowDate());
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = multipartRequest.getFile("file");
            if (file.isEmpty()) {
                return "文件不能为空";
            }
            InputStream inputStream = file.getInputStream();
            log.info("\n【请求地址】：{}\n【请求时间】：{}\n【上传文件名】：{}", "/upload", VeDate.getNowDate(), file.getOriginalFilename());
            uploadExecutor.executeUpload(inputStream, file.getOriginalFilename());
            System.gc();
            JSONObject object = new JSONObject();
            object.put("result","true");
            return object.toJSONString();
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败。";
        }
    }


}
